package com.me.study.concurrent;

import org.junit.Assert;

/**
 * 测试 cache line 带来的性能提升：https://tech.meituan.com/2016/11/18/disruptor.html     <p>
 * Cache 由很多个 cache line 组成，每个 cache line通常是 64字节，并且它有效地引用主内存中的一块儿地址。   <p>
 * 一个 long类型变量是 8字节，因此在一个缓存行中可以存 8个long类型的变量。   <p>
 *
 * @author ME
 * @date 2021/9/9
 */
public class TestCacheLineEffect {

    /** 考虑一般缓存行大小是64字节，一个 long 类型占8字节 */
    private static final long[][] ARR = new long[1024 * 1024][];

    public static void main(String[] args) {
        long sum1 = 0L;
        long marked = System.currentTimeMillis();
        for (int i = 0; i < 1024 * 1024; i += 1) {
            for (int j = 0; j < 8; j++) {
                sum1 = ARR[i][j];
            }
        }
        System.out.println("Loop times:" + (System.currentTimeMillis() - marked) + "ms");

        long sum2 = 0L;
        marked = System.currentTimeMillis();
        for (int i = 0; i < 8; i += 1) {
            for (int j = 0; j < 1024 * 1024; j++) {
                sum2 = ARR[j][i];
            }
        }
        System.out.println("Loop times:" + (System.currentTimeMillis() - marked) + "ms");

        System.out.println("求和：" + sum1);
        Assert.assertEquals(sum1, sum2);
    }

    static {
        int number = 1;
        for (int i = 0; i < 1024 * 1024; i++) {
            ARR[i] = new long[8];
            for (int j = 0; j < 8; j++) {
                ARR[i][j] = number++;
            }
        }
    }

}
